const arrText = ['正向有功', '正向无功', '反向有功', '反向有功'];
const code = [
  { text: '换表前表码', code: '02' },
  { text: '换表后初始表码', code: '01' },
];
const arrValue = ['总', '尖', '峰', '平', '谷'];

function combinationData() {
  const obj = {};
  code.forEach((items) => {
    const name = 'code' + items.code;
    obj[name] = {
      text: items.text,
      children: [],
    };
    arrText.forEach((textItem, index) => {
      obj[name].children[index] = {
        text: textItem,
        children: [],
      };
      arrValue.forEach((value, i) => {
        const code = `1000000${index + 1}0${i}`;
        obj[name].children[index].children.push({
          text: value,
          dataItemCode: code,
          cReading: '',
          removeType: items.code,
        })
      })
    })
  });
  return obj;
}

const meterCode = combinationData();

function deepFirstSearch(meterCode = {}, objs) {
  let j = 0;
  Object.keys(meterCode).forEach((key) => {
    const node = meterCode[key];
    if (node != null) {
      const stack = [];
      stack.push(node);
      while (stack.length) {
        const item = stack.pop();
        const { dataItemCode, removeType, children } = item;
        if (dataItemCode && removeType) {
          if (Array.isArray(objs)) {
            objs.push(item)
          } else {
            const names = removeType + '-' + dataItemCode;
            item.cReading = objs[names] ? objs[names].cReading : '';
            item.index = j ++;
          }
        }
        if (children == null) {
          continue;
        }
        for (let i = children.length - 1; i >= 0; i --) {
          stack.push(children[i]);
        }
      }
    }
  });
  return Array.isArray(objs) ? objs : null;
}

function fillingMeterCode(data) {
  const obj = Object.create(null);
  (data || []).forEach((item) => {
    const name = item.removeType + '-' + item.dataItemCode;
    obj[name] = item;
  });

  deepFirstSearch(meterCode, obj);
  return meterCode;
}

function getMeterCode(data) {
  const arr = [];
  return deepFirstSearch(data, arr);
}

export {
  getMeterCode,
  fillingMeterCode
};
